package com.lgy.service;

import com.lgy.exceptions.BusinessException;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProcessServiceImpl implements IProcessService {
    @Resource
    private RuntimeService runtimeService ;
    @Resource
    private TaskService taskService;

    @Override
    public String startProcessFirst(String applyUserId,String approvalUserId, String processDefKey) {
        Map<String, Object> variables = new HashMap<>() ;
        variables.put("apply", applyUserId) ;
        variables.put("approval", approvalUserId);
        //启动一个流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefKey,variables);

        //完成第一个节点任务
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
        if(!task.getAssignee().equals(applyUserId)) {
            throw new BusinessException("发起流程失败！");
        }
        taskService.complete(task.getId());
        return processInstance.getId();
    }
}
